<?php

/**
 * 
 * @author 
 *
 * @desc It's ugly (
 *
 */
class gMail extends gCoreObject
{
	protected $_letter = array(
		'to' => null,
		'from'=>null,
		'subject'=>null,
		'body'=>null,
		'content-type'=>null,
		'cc'=>null,
		'reply'=>null,
		'headers'=>null
	);
	
	public function subject($text)
	{
		$this->_letter['subject'] = $text;
		return $this;
	}
	
	public function to($email, $name = null)
	{
		if( $this->_letter['to']){
			$this->_letter['to'] .=' , '.$this->setName($email, $name);
		} else {
			$this->_letter['to'] = 'To: '.$this->setName($email, $name);
		}
		return $this;
	}
	
	public function cc($email, $name = null)
	{
		if( $this->_letter['cc']){
			$this->_letter['cc'] .=' , '.$this->setName($email, $name);
		} else {
			$this->_letter['cc'] = 'Cc: '.$this->setName($email, $name);
		}
		return $this;;
	}
	
	public function from($email, $name = null)
	{
		if( $this->_letter['from']){
			$this->_letter['from'] .=' , '.$this->setName($email, $name);
		} else {
			$this->_letter['from'] = 'From: '.$this->setName($email, $name);
		}
		return $this;
	}
	
	public function reply($email,$name = null)
	{
		if( $this->_letter['reply']){
			$this->_letter['reply'] .=' , '.$this->setName($email, $name);
		} else {
			$this->_letter['reply'] = 'Reply-To: '.$this->setName($email, $name);
		}
		return $this;		
	}
	
	
	private function setName($email, $name)
	{
		return $name ? '"'.$name.'" <'.$email.'>' : $email;
	}
	
	public function message($data)
	{
		$this->_letter['content-type'] = 'Content-type: text/html; charset=utf-8';
		$this->_letter['body'] .= $data;
		return $this;
		
	}
	
	public function text($data)
	{
		$this->_letter['body'] .= $data;
		return $this;
	}
	
	private function addHeader($name,$value)
	{
		$this->_letter['headers'] .= $name.': '.$value.PHP_EOL;
	}
	
	public function attach($filename)
	{
		$this->_letter['content-type'] = 'Content-type: multipart/mixed; boundary=_message_boundary_';
		return $this;
	}
	
	public function send()
	{
		
		$headers = null;
		if( $this->_letter['from'])
			$headers .= $this->_letter['from'].PHP_EOL;
		if( $this->_letter['cc'])
			$headers .= $this->_letter['cc'].PHP_EOL;
		if( $this->_letter['reply'])
			$headers .= $this->_letter['reply'].PHP_EOL;
		if( $this->_letter['content-type'])
			$headers .= $this->_letter['content-type'].PHP_EOL;
		if( $this->_letter['headers'])
			$headers .= $this->_letter['headers'].PHP_EOL;
		
		var_dump(mail($this->_letter['to'],$this->_letter['subject'],$this->_letter['body'],$headers));
		
		foreach( $this->_letter as $key=>&$value)
		{
			$value =  null;
		}
		
	}	
	
	function __toString()
	{
		return implode(PHP_EOL, $this->_letter);
	}
	
}